package cn.itsource.pet.controller;

import cn.itsource.org.domain.Department;
import cn.itsource.org.domain.Employee;
import cn.itsource.org.domain.Shop;
import cn.itsource.org.service.IShopService;
import cn.itsource.pet.domain.Pet;
import cn.itsource.pet.query.PetQuery;
import cn.itsource.pet.service.IPetService;
import cn.itsource.utils.AjaxResult;
import cn.itsource.utils.LoginContext;
import cn.itsource.utils.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/pet")
public class PetController {

    @Autowired
    private IShopService shopService;

    @Autowired
    private IPetService petService;

    @PostMapping
    public PageResult<Pet> queryPage(@RequestBody PetQuery query,HttpServletRequest request){
        //获取当前系统的登录用户
        Employee employee= (Employee) LoginContext.getCurrent(request);
        //当前用户对应的店铺
        Shop shop = shopService.loadByAdminId(employee.getId());
        //把店铺的id作为一个查询条件 传入到query里面
        query.setShopId(shop.getId());

        return petService.queryPage(query);
    }

    @PostMapping("/front")
    public PageResult<Pet> queryPageOfFront(@RequestBody PetQuery query){

        return petService.queryPage(query);
    }

    @GetMapping("/detail/{id}")
    public Pet detail(@PathVariable("id") Long id){

        return petService.loadByIdOfFront(id);
    }

    @PutMapping
    public AjaxResult saveOrUpdate(@RequestBody Pet pet,HttpServletRequest request){
        System.out.println(pet);
        try {
            //获取当前系统的登录用户
            Employee employee= (Employee) LoginContext.getCurrent(request);
            //当前用户对应的店铺
            Shop shop = shopService.loadByAdminId(employee.getId());
            pet.setShop_id(shop.getId());
            if (pet.getId()!=null){
                petService.update(pet);
            }else {
                petService.save(pet);
            }
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage(e.getMessage());
        }

    }

    @PatchMapping("/onSale")
    public AjaxResult onSale(@RequestBody Long[] ids) {
        try {
            petService.onSale(ids);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage(e.getMessage());
        }
    }
}
